package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.workcellinfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.RelatedDocMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.WorkCellInfoMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.WorkCellInstanceMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.workcellinfo.JsmIRelatedDocService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by jiangjx on 2017/1/4.
 */

public class JsmRelatedDocServiceImpl implements JsmIRelatedDocService {

    @Autowired
    private RelatedDocMapper relatedDocMapper;


    @Autowired
    private WorkCellInfoMapper workCellInfoMapper;

    @Autowired
    private WorkCellInstanceMapper workCellInstanceMapper;


    /**
     * 根据操作单元ID查询出关联文档列表（带分页）
     *
     * @param relatedDoc 操作单元或者一站一案
     * @param isStatus   状态   isStatus
     */
    @Override
    public JSONObject loadTable(RelatedDoc relatedDoc, String isStatus) throws Exception {
        JSONObject jsonObject = new JSONObject();
        List<RelatedDoc> baseRows = new ArrayList<>();
        /* 进行分页查询分离 */
        if (isStatus.equals("modify")) {
            BigDecimal version = relatedDoc.getVersion();
            // relatedDoc
            relatedDoc.setVersion(null);
            baseRows = relatedDocMapper.queryTableList(relatedDoc); //查询分页内容
            if (baseRows == null || baseRows.size() == 0) {
                relatedDoc.setVersion(version);
                baseRows = relatedDocMapper.queryTableList(relatedDoc);
            }
        } else {
            baseRows = relatedDocMapper.queryTableList(relatedDoc); //查询分页内容
        }

        /*将查询出来的原始数据进行处理*/
        List<RelatedDocVo> returnRows = new ArrayList<>();
        for (RelatedDoc doc : baseRows) {
            RelatedDocVo docVo = new RelatedDocVo();
            BeanUtils.copyProperties(docVo, doc);
            returnRows.add(docVo);
        }
        /*返回结果*/
        jsonObject.put("rows", JSON.toJSON(returnRows));
        return jsonObject;
    }


    /**
     * 删除文档配置
     * created by jiangjx
     *
     * @param cellRelatedDocId 文档关联id
     * @return
     */
    @Override
    public Integer delDocTable(String cellRelatedDocId, Employee employee) throws Exception {

        JSONArray ids = JSONObject.parseArray(cellRelatedDocId);
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);//set要删除的数据的ids
        map.put("modifyId", employee.getEmployeeId());//修改人id
        map.put("modifyTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));//修改时间
        int rowNumb = relatedDocMapper.updateDocByIds(map);//逻辑删除文档配置信息
        if (rowNumb > 0) {
            return rowNumb;
        } else {
            return 0;
        }
    }

    /**
     * 保存文档配置信息
     * created by jiangjx
     *
     * @param relatedDocVo 新增数据封装类
     * @return
     */
    @Override
    public Integer saveDocInfo(RelatedDocVo relatedDocVo, Employee employee) throws Exception {
        Integer resInt = 0;
        //Employee employee = employeeService.getLoginEmployee();
        BigDecimal oldVersion = null;
        // ** 保存文档 的时候判断是否存在为空的版本 ， 如果不存在为空的版本 则复制当前版本 并设置为空
        if (relatedDocVo.getCellId() != null) {
            // 要么操作单元 要么 一站一案
            WorkCellInfo workCellInfo = workCellInfoMapper.selectByPrimaryKey(relatedDocVo.getCellId());
            // 操作单元 复制当前操作单元文档
            if (workCellInfo != null && workCellInfo.getStepVersion() != null) {
                oldVersion = workCellInfo.getStepVersion();
            } else {
                // 一站一案 复制当前一站一案的文档
                WorkCellInstance workCellInfoVo = workCellInstanceMapper.selectByPrimaryKey(relatedDocVo.getCellId());
                if (workCellInfoVo != null && workCellInfoVo.getStepVersion() != null) {
                    oldVersion = workCellInfoVo.getStepVersion();
                }
            }
            RelatedDoc related = new RelatedDoc();
            related.setCellId(relatedDocVo.getCellId());
            List<RelatedDoc> isRelatedDocList = relatedDocMapper.queryTableList(related);
            // 判断当前是否存在空版本则新增当前文档， 如果不存在空版本 则复制上一个版本的文档
            List<RelatedDoc> addRelatedDocList = new ArrayList<RelatedDoc>();
            if (isRelatedDocList == null || isRelatedDocList.size() == 0) {
                // 判断当前是否存在空版本，复制上一个版本的文档
                related.setVersion(oldVersion);
                List<RelatedDoc> relatedDocs = relatedDocMapper.queryTableList(related);
                // 判断上一个文档是否为空
                if (relatedDocs != null && relatedDocs.size() > 0) {
                    for (RelatedDoc rds : relatedDocs) {
                        rds.setCellRelatedDocId(UniqueUtil.uuid());//set主键ID
                        rds.setCreatorId(employee.getEmployeeId());//set创建人ID
                        rds.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));//set创建时间
                        rds.setModifierId(employee.getEmployeeId());//set修改人ID
                        rds.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));//set修改时间
                        rds.setVersion(null);
//                        relatedDocMapper.insertSelective(rds);
                        addRelatedDocList.add(rds);
                    }
                }
            }
            RelatedDoc relatedDoc = new RelatedDoc();
            BeanUtils.copyProperties(relatedDoc, relatedDocVo);//将页面传递的值复制到po类中
            String[] relatedDocTypeStr = relatedDoc.getDocName().split("\\.");
            if (relatedDocTypeStr != null && relatedDocTypeStr.length > 0) {
                relatedDoc.setDocType(relatedDocTypeStr[relatedDocTypeStr.length - 1]);//set文档类型
            }
            relatedDoc.setCellRelatedDocId(UniqueUtil.uuid());//set主键ID
            relatedDoc.setCreatorId(employee.getEmployeeId());//set创建人ID
            relatedDoc.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));//set创建时间
            relatedDoc.setModifierId(employee.getEmployeeId());//set修改人ID
            relatedDoc.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));//set修改时间
            relatedDoc.setIsdelete(Short.parseShort("0"));//set删除标识位为未删除
            addRelatedDocList.add(relatedDoc);
            resInt = relatedDocMapper.insertList(addRelatedDocList);
        }
        return resInt;
    }

    /**
     * 操作单元 或者 一站一案 版本控制  ；
     *
     * @param version    新增版本的版本信息 ；
     * @param isWorkCell 是否是一站一案  ；
     * @param oldVersion 当前在用版本问题；
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> cloneDoc(Version version, boolean isWorkCell, BigDecimal oldVersion, Employee employee) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        RelatedDoc relatedDoc = new RelatedDoc();
        relatedDoc.setCellId(version.getRelatedId());
        List<RelatedDoc> relatedDocs = relatedDocMapper.queryTableList(relatedDoc);
        // 关联文档非空判断，查询当前文档版本为空的文档列表
        String creatorId = employee.getEmployeeId();
        if (relatedDocs != null && relatedDocs.size() > 0) {
            for (RelatedDoc rd : relatedDocs) {
                rd.setCreatorId(creatorId);
                rd.setModifierId(creatorId);
                rd.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                rd.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                rd.setVersion(version.getVersionNumber());
                relatedDocMapper.updateByPrimaryKeySelective(rd);
            }
        } else {
            relatedDoc.setVersion(oldVersion);
            List<RelatedDoc> OldRelatedDocs = relatedDocMapper.queryTableList(relatedDoc);
            if (OldRelatedDocs != null && OldRelatedDocs.size() > 0) {
                for (RelatedDoc rds : OldRelatedDocs) {
                    rds.setCellRelatedDocId(UniqueUtil.uuid());
                    rds.setCreatorId(creatorId);
                    rds.setModifierId(creatorId);
                    rds.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                    rds.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                    rds.setVersion(version.getVersionNumber());
                    relatedDocMapper.insertSelective(rds);
                }
            }
        }

        return resMap;
    }

    /**
     * 新增一站一案，将操作单元的文档复制到一站一案
     *
     * @param fromWorkCellInfo   操作单元
     * @param toWorkCellInstance 一站一案
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Map<String, Object> cloneDoc(WorkCellInfo fromWorkCellInfo, WorkCellInstance toWorkCellInstance, Employee employee) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        if (fromWorkCellInfo != null && fromWorkCellInfo.getStepVersion() != null) {
            RelatedDoc relatedDoc = new RelatedDoc();
            relatedDoc.setCellId(fromWorkCellInfo.getCellId());
            relatedDoc.setVersion(fromWorkCellInfo.getStepVersion());
            List<RelatedDoc> relatedDocs = relatedDocMapper.queryTableList(relatedDoc);
            // 关联文档非空判断
            if (relatedDocs != null && relatedDocs.size() > 0) {
                String creatorId = employee.getEmployeeId();
                for (RelatedDoc rd : relatedDocs) {
                    rd.setCreatorId(creatorId);
                    rd.setModifierId(creatorId);
                    rd.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                    rd.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                    rd.setCellRelatedDocId(UniqueUtil.uuid());
                    rd.setVersion(null);
                    rd.setCellId(toWorkCellInstance.getWorkInstanceId());
                    relatedDocMapper.insertSelective(rd);
                }
            }
        }
        return resMap;
    }

    /**
     * @param formInstance
     * @param toInstance
     * @param employeeVo
     * @throws Exception 一站一案的文档复制
     */
    @Override
    public Map<String, Object> cloneDoc(WorkCellInstance formInstance, WorkCellInstance toInstance, EmployeeVo employeeVo) throws Exception {
        Map<String,Object> resMap = new HashMap<>();
        List<RelatedDoc>  relatedDocList = relatedDocMapper.selectRelaedDocList(formInstance);
        if(relatedDocList != null && relatedDocList.size() > 0){
            for(RelatedDoc relatedDoc : relatedDocList){
                relatedDoc.setCellRelatedDocId(UniqueUtil.uuid());
                relatedDoc.setCreatorId(employeeVo.getEmployeeId());
                relatedDoc.setModifierId(employeeVo.getEmployeeId());
                relatedDoc.setCellId(toInstance.getWorkInstanceId());
                relatedDoc.setCreateTime(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                relatedDoc.setModifyTime(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                relatedDoc.setVersion(null);
                relatedDocMapper.insertSelective(relatedDoc);
            }
        }
        resMap.put("state",true);
        resMap.put("msg","一站一案文档复制成功");
        return resMap ;
    }
}
